package com.lv.service.ui

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.core.content.PermissionChecker
import androidx.viewpager2.widget.ViewPager2
import cc.shinichi.library.ImagePreview
import cc.shinichi.library.tool.image.DownloadPictureUtil
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.lv.common.base.BaseActivity
import com.lv.common.utils.ARoutUtils
import com.lv.common.utils.PermissionXUtils
import com.lv.common.utils.PermissionXUtilsCallback
import com.lv.service.R
import com.lv.service.adapter.MediaTypeAdapter
import com.lv.service.bean.ViewTypeStringBean
import com.lv.service.databinding.ActivityShowMediaDetailsBinding


/**
 * 作者： ygx
 * 创建日期：2023/3/28 5:51 PM
 * 签名： 天行健，君子以自强不息；地势坤，君子以厚德载物。
 * -    _              _           _     _   ____  _             _ _
 * -   / \   _ __   __| |_ __ ___ (_) __| | / ___|| |_ _   _  __| (_) ___
 * -  / _ \ | '_ \ / _` | '__/ _ \| |/ _` | \___ \| __| | | |/ _` | |/ _ \
 * - / ___ \| | | | (_| | | | (_) | | (_| |  ___) | |_| |_| | (_| | | (_) |
 * -/_/   \_\_| |_|\__,_|_|  \___/|_|\__,_| |____/ \__|\__,_|\__,_|_|\___/
 * <p>
 * You never know what you can do until you try !
 * ----------------------------------------------------------------
 * 描述：视频、图片点击放大页面
 */
@Route(path = ARoutUtils.ShowMediaDetailsActivity)
class ShowMediaDetailsActivity : BaseActivity<ActivityShowMediaDetailsBinding>(),
    View.OnClickListener {
    @Autowired(name = "position")
    @JvmField
    var currentPosition: Int = 0

    var tempPosition: Int = 0

    @Autowired(name = "data")
    @JvmField
    var jsonData = ""
    private var mBeans: List<ViewTypeStringBean>? = null
    private var isShowDownButton = true
    private var isShowIndicator = true
    private var indicatorStatus = false
    private var downloadButtonStatus = false
//    private val PERMISSIONS_STORAGE = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
//        arrayOf(
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,
//            Manifest.permission.MANAGE_EXTERNAL_STORAGE,
//        )
//    } else {
//        arrayOf(
//            Manifest.permission.READ_EXTERNAL_STORAGE,
//            Manifest.permission.WRITE_EXTERNAL_STORAGE,
//        )
//    }
    private var mAdapter: MediaTypeAdapter? = null
    private var mFacoryDatas = mutableListOf<ViewTypeStringBean>()

    private var currentPositionOriginPathUrl: String? = ""

    override fun getLayoutRes() = R.layout.activity_show_media_details
    override fun initView() {
        super.initView()
        initStatusBar(this, true, false)
        ARouter.getInstance().inject(this)
    }


    override fun initConfig() {
        super.initConfig()
        if (intent != null) {
            jsonData = intent.getStringExtra("data") ?: ""
            currentPosition = intent.getIntExtra("position", 0)
        }
        if (jsonData.isNotEmpty()) {
            val listType = object : TypeToken<List<ViewTypeStringBean>>() {}.type
            mBeans = Gson().fromJson(jsonData, listType)
        }
//        mBeans = intent.getParcelableArrayListExtra("data", ViewTypeBean::class.java)
        mBeans?.let {
            mFacoryDatas.clear()
            mFacoryDatas.addAll(it)
        }
        mAdapter = MediaTypeAdapter(mFacoryDatas)
        mBinding.viewPager.adapter = mAdapter
        mBinding.viewPager.currentItem = currentPosition
        currentPositionOriginPathUrl = mBeans?.get(currentPosition)?.data
        mBinding.imgDownload.setOnClickListener(this)
        mBinding.imgCloseButton.setOnClickListener(this)
        indicatorStatus = if (!isShowIndicator) {
            mBinding.tvIndicator.visibility = View.GONE
            false
        } else {
            if (mBeans.isNullOrEmpty() && mBeans!!.size > 1) {
                mBinding.tvIndicator.visibility = View.VISIBLE
                true
            } else {
                mBinding.tvIndicator.visibility = View.GONE
                false
            }
        }
        // 设置顶部指示器背景shape
        if (ImagePreview.instance.indicatorShapeResId > 0) {
            mBinding.tvIndicator.setBackgroundResource(ImagePreview.instance.indicatorShapeResId)
        }
        downloadButtonStatus = if (isShowDownButton) {
            mBinding.imgDownload.visibility = View.VISIBLE
            true
        } else {
            mBinding.imgDownload.visibility = View.GONE
            false
        }

        mBinding.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                ImagePreview.instance.bigImagePageChangeListener?.onPageScrollStateChanged(state)
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)
            }

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentPosition = position
                val type = mBeans?.get(position)?.type
                val tempType = mBeans?.get(tempPosition)?.type
                if (tempType == ViewTypeStringBean.VEDIO_TYPE) {
                    mAdapter?.getMyvideo()?.currentPlayer?.onVideoPause()
                }
                if (type == ViewTypeStringBean.VEDIO_TYPE) {
                    val videoPlayer = mAdapter?.getMyvideo()
                    videoPlayer?.startPlayLogic()
//                    mAdapter?.getMyvideo()?.currentPlayer?.onVideoResume(false)
//                    mAdapter?.getMyvideo()?.startButton?.performClick()
                }
                ImagePreview.instance.bigImagePageChangeListener?.onPageSelected(currentPosition)
                currentPositionOriginPathUrl = mBeans!![currentPosition].data

                // 更新进度指示器
                mBinding.tvIndicator.text = String.format(
                    getString(cc.shinichi.library.R.string.indicator),
                    (currentPosition + 1).toString(),
                    (mBeans?.size).toString()
                )
                tempPosition = position
            }
        })


    }


    /**
     * 下载当前图片到SD卡
     */
    private fun downloadCurrentImg() {
        val type = mBeans?.get(currentPosition)?.type
        var typeU: String =
            currentPositionOriginPathUrl!!.substring(currentPositionOriginPathUrl!!.lastIndexOf("."))
        if (typeU.startsWith(".")) {
            typeU = typeU.substring(1, typeU.length)
        }
        if (type == 0) {
            ImagePreview.instance.folderFileType = ""
        } else {
            ImagePreview.instance.folderFileType = typeU
        }
        DownloadPictureUtil.downloadPicture(this, currentPosition, currentPositionOriginPathUrl)
    }

    override fun initData() {
        super.initData()

    }

    override fun onClick(v: View) {
        val i = v.id
        if (i == cc.shinichi.library.R.id.img_download) {
            val downloadClickListener = ImagePreview.instance.downloadClickListener
            if (downloadClickListener != null) {
                val interceptDownload = downloadClickListener.isInterceptDownload
                if (interceptDownload) {
                    // 拦截了下载，不执行下载
                } else {
                    // 没有拦截下载
                    checkAndDownload()
                }
                ImagePreview.instance.downloadClickListener?.onClick(this, v, currentPosition)
            } else {
                checkAndDownload()
            }
        } else if (i == cc.shinichi.library.R.id.btn_show_origin) {
//            handlerHolder.sendEmptyMessage(0)
        } else if (i == cc.shinichi.library.R.id.imgCloseButton) {
            finish()
        }
    }

    private fun checkAndDownload() {
        val permissions = mutableListOf<String>()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
        } else {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        PermissionXUtils.checkPermissBefore(
            this,
            permissions,
            "请授予存储权限，以便保存图片到手机相册",
            callback = object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        // 下载当前图片
                        downloadCurrentImg()
                    }
                }
                override fun fotPermsission() {

                }
            })
    }
    private fun checkPermission() {
        val permissions = mutableListOf(
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
        )
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            permissions.add(Manifest.permission.READ_MEDIA_IMAGES)
//            permissions.add(Manifest.permission.READ_MEDIA_AUDIO)
//            permissions.add(Manifest.permission.READ_MEDIA_VIDEO)
        } else {
            permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE)
        }
        PermissionXUtils.checkPermissBefore(
            this@ShowMediaDetailsActivity,
            permissions,
            "请授予存储权限，以便保存图片到手机相册",
            callback = object : PermissionXUtilsCallback {
                override fun permissionCallback(
                    allGranted: Boolean,
                    grantedList: List<String?>,
                    deniedList: List<String?>
                ) {
                    if (allGranted) {
                        downloadCurrentImg()
                    }
                }
                override fun fotPermsission() {

                }
            })
    }


//    override fun onRequestPermissionsResult(
//        requestCode: Int, permissions: Array<String>,
//        grantResults: IntArray
//    ) {
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
//        if (requestCode == 1) {
//            for (i in permissions.indices) {
//                if (grantResults[i] == PermissionChecker.PERMISSION_GRANTED) {
//                    downloadCurrentImg()
//                }
//            }
//        }
//    }


    override fun onResume() {
        mAdapter?.getMyvideo()?.currentPlayer?.onVideoResume(false)
        super.onResume()
    }

    override fun onPause() {
        mAdapter?.getMyvideo()?.currentPlayer?.onVideoPause()
        super.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mAdapter?.getMyvideo()?.currentPlayer?.release()
    }

}